﻿# -*- coding: utf-8 -*-

"""
Module implementing MainWindow.
"""

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from .Ui_MainWindow import Ui_MainWindow
import os, glob, re

class MainWindow(QMainWindow, Ui_MainWindow):
    """
    Class documentation goes here.
    """
    def __init__(self, parent=None):
        """
        Constructor

        @param parent reference to the parent widget (QWidget)
        """
        super().__init__(parent)
        self.setupUi(self)

    def _getSelected(self):
        rows = [i.row() for i in self.songTable.selectedIndexes()]
        rows = list(set(rows))
        rows.sort()
        return rows

    def _parse(self, file):
        ptn1 = re.compile(r'[　 .]*[-－—]+[ 　.]*')   #to split
        ptn2 = re.compile(r'[(（\[].+?[)）\]]')   #to del (string)
        (path, name) = os.path.split(file)
        (name, ext) = os.path.splitext(name)
        name = ptn2.sub('', name)   #del (string)
        (singer, song) = ptn1.split(name)[:2]
        singer = re.split('_',singer)[0]
        song = re.split('_',song)[0]
        newname = singer+'-'+song+ext
        new =  {'singer':singer, 'song':song, 'ext':ext, 'newname':newname}
        return new

    @pyqtSlot()
    def on_action_Exit_triggered(self):
        print('ok')
        self.close()

    @pyqtSlot()
    def on_addButton_clicked(self):
        """
        Slot documentation goes here.
        """
        files = QFileDialog.getOpenFileNames(self, r'选择歌曲文件', '', r"视频文件 (*.mkv *.mpg *.mp4 *.avi *.dat)")
##        print(files)
        for i in range(len(files)):
            file = files[i]
            self.songTable.insertRow(i)
            self.songTable.setItem(i, 3, QTableWidgetItem(file))
            try:
                new = self._parse(file)
                self.songTable.setItem(i, 0, QTableWidgetItem(new['singer']))
                self.songTable.setItem(i, 1, QTableWidgetItem(new['song']))
                self.songTable.setItem(i, 2, QTableWidgetItem(new['ext']))
                self.songTable.setItem(i, 4, QTableWidgetItem(new['newname']))
            except:
                pass

    @pyqtSlot()
    def on_deleteButton_clicked(self):
        rows = self._getSelected()
        rows.reverse()
        for i in rows:
            try:
                self.songTable.removeRow(i)
            except:
                pass

    @pyqtSlot()
    def on_parseSong_clicked(self):
        rows = self._getSelected()
        for i in rows:
            try:
                new = self._parse(self.songTable.item(i, 3).text())
                self.songTable.setItem(i, 0, QTableWidgetItem(new['singer']))
                self.songTable.setItem(i, 1, QTableWidgetItem(new['song']))
                self.songTable.setItem(i, 2, QTableWidgetItem(new['ext']))
                self.songTable.setItem(i, 4, QTableWidgetItem(new['newname']))
            except:
                pass

    @pyqtSlot()
    def on_chgBtn_clicked(self):
        rows = self._getSelected()
        for i in rows:
            singer = self.songTable.item(i, 1).text()
            song = self.songTable.item(i, 0).text()
            ext = self.songTable.item(i, 2).text()
            newname = singer+'-'+song+ext
            self.songTable.setItem(i, 0, QTableWidgetItem(singer))
            self.songTable.setItem(i, 1, QTableWidgetItem(song))
            self.songTable.setItem(i, 4, QTableWidgetItem(newname))

    @pyqtSlot()
    def on_frsBtn_clicked(self):
        rows = self._getSelected()
        for i in rows:
            try:
                singer = self.songTable.item(i, 0).text()
                song = self.songTable.item(i, 1).text()
                ext = self.songTable.item(i, 2).text()
                newname = singer+'-'+song+ext
                self.songTable.setItem(i, 4, QTableWidgetItem(newname))
            except:
                pass

    @pyqtSlot()
    def on_svBtn_clicked(self):
        rows = self.songTable.rowCount()
        for i in range(rows):
            try:
                oldfile = self.songTable.item(i, 3).text()
                oldname = os.path.split(oldfile)[1]
                newname = self.songTable.item(i, 4).text()
                newfile = os.path.split(oldfile)[0]+'\\'+newname
                if newname != oldname:
                    if glob.glob(newfile):
                        newfile = os.path.split(oldfile)[0]+'\\重名.'+newname
                        os.rename(oldfile, newfile)
                        tip = "重名歌曲："+newname+'\n'+'已重命名为：重名.'+newname
                        msg = QMessageBox(self)
                        msg.setWindowTitle('确认信息')
                        msg.setText(tip)
                        msg.exec()
                    else:
                        print(newfile)
                        os.rename(oldfile, newfile)
                else:
                    pass
            except:
                pass
        msg = QMessageBox(self)
        msg.setWindowTitle('确认信息')
        msg.setText("更新完毕\t")
        msg.exec()

    @pyqtSlot()
    def on_delBtn_clicked(self):
        rows = self._getSelected()
        for i in rows:
            try:
                os.remove(self.songTable.item(i, 3).text())
            except:
                pass
            else:
                self.songTable.removeRow(i)






